package com.fita.admin.service.agent.impl;

import com.demo2do.core.entity.exception.BusinessException;
import com.demo2do.core.entity.page.Page;
import com.demo2do.core.persistence.GenericDaoSupport;
import com.demo2do.core.persistence.annotation.Dao;
import com.demo2do.core.persistence.support.QueryFilter;
import com.fita.admin.dao.AgentCompanyDao;
import com.fita.admin.dao.AgentDao;
import com.fita.admin.entity.security.Login;
import com.fita.admin.service.DataServiceImpl;
import com.fita.admin.service.agent.AgentService;
import com.fita.entity.agent.Agent;
import com.fita.entity.agent.AgentCompany;
import org.apache.commons.lang3.ClassUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 
 * @author cuteHU
 *
 */
@Service("agentService")
public class AgentServiceImpl extends DataServiceImpl<Agent> implements AgentService {

    @Dao
    private AgentDao agentDao;

    @Autowired
    private GenericDaoSupport genericDaoSupport;

    @Dao
    private AgentCompanyDao agentCompanyDao;


    /*
     * (non-Javadoc)
     * 
     * @see com.fita.admin.service.agent.AgentService#list(com.fita.entity.agent.
     * AgentCompany)
     */
    public List<Agent> list(AgentCompany agentCompany) {
        return agentDao.list(agentCompany);
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * com.fita.admin.service.agent.AgentService#countAgentCompany(java.lang.Class)
     */
    public int countAgentCompany(Class<AgentCompany> clazz) {
        return genericDaoSupport.searchForInt("SELECT COUNT(*) FROM " + ClassUtils.getShortClassName(clazz));
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * com.fita.admin.service.agent.AgentService#listAgentCompany(com.demo2do.core.
     * entity.page.Page)
     */
    public List<AgentCompany> listAgentCompany(Page page) {
        return agentDao.listAgentCompany(page.getBeginIndex(), page.getMaxResultRecords());
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.fita.admin.service.agent.AgentService#countSearch(java.lang.Class,
     * com.demo2do.core.persistence.support.QueryFilter)
     */
    public int countSearch(Class<AgentCompany> clazz, QueryFilter queryFilter) {
        return genericDaoSupport.searchForInt(
                "SELECT COUNT(*) FROM " + ClassUtils.getShortClassName(clazz) + queryFilter.whereSentence(),
                queryFilter.parameters());
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * com.fita.admin.service.agent.AgentService#updateAgentCompany(com.fita.entity.
     * agent.AgentCompany)
     */
    public void updateAgentCompany(AgentCompany agentCompany) {
        genericDaoSupport.update(agentCompany);
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * com.fita.admin.service.agent.AgentService#freezeAgent(com.fita.entity.agent.
     * Agent)
     */
    public void freezeAgent(Agent agent) {
        agent.freeze();
        genericDaoSupport.update(agent);
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * com.fita.admin.service.agent.AgentService#activateAgent(com.fita.entity.agent
     * .Agent)
     */
    public void activateAgent(Agent agent) {
        agent.activate();
        genericDaoSupport.update(agent);
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * com.fita.admin.service.agent.AgentService#countAgentCompany(com.fita.admin.
     * entity.security.Login)
     */
    public int countAgentCompany(Login login) {
        if (login.isAdmin()) {
            return agentDao.countAll();
        } else {
            return agentDao.countOther(login.getDistrict());
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * com.fita.admin.service.agent.AgentService#listAgentCompany(com.demo2do.core.
     * entity.page.Page, com.fita.admin.entity.security.Login)
     */
    public List<AgentCompany> listAgentCompany(Page page, Login login) {
        if (login.isAdmin()) {
            List<AgentCompany> agentCompanies = agentDao.listAgentCompany(page.getBeginIndex(), page.getEveryPage());
            page.calculate();
            return agentCompanies;
        } else {
            List<AgentCompany> agentCompanies = agentDao.list(page.getBeginIndex(), page.getEveryPage(),
                    login.getDistrict());
            page.calculate();
            return agentCompanies;
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.fita.admin.service.agent.AgentService#load(java.lang.String)
     */
    public AgentCompany loadByName(String name) {
        return agentDao.load(name);
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.fita.admin.service.agent.AgentService#edit(java.lang.Long,
     * com.fita.entity.agent.AgentCompany)
     */
    public void edit(Long id, AgentCompany agentCompany) {
        List<AgentCompany> loads = agentDao.loads(agentCompany.getName());
        AgentCompany load = genericDaoSupport.load(AgentCompany.class, id);
        // 如果代理名称没有修改，更新
        if (agentCompany.getName().equals(load.getName())) {
            genericDaoSupport.update(load.edit(agentCompany));
        } else if (loads.size() > 0) {
            throw BusinessException.newInstance("400", "代理名称不可重复！");
        }

        // 如果该公司为一级代理
        if (agentCompany.getPrimaryAgent() == null){

            List<AgentCompany> secondaryAgentCompanies = agentCompanyDao.listSecondaryAgentCompanyByPrimaryAgentCompany(agentCompany);

            secondaryAgentCompanies.stream().forEach(secondaryAgentCompany -> {
                secondaryAgentCompany.changRate(agentCompany.getRate());
                genericDaoSupport.update(secondaryAgentCompany);
            });
        }


    }

    /* (non-Javadoc)
     * @see com.fita.admin.service.agent.AgentService#editAgent(java.lang.Long, com.fita.entity.agent.Agent)
     */
    public void editAgent(Long agentId, Agent agent) {
        List<Agent> loads = agentDao.loadAgents(agent.getMobile());
        Agent load = genericDaoSupport.load(Agent.class, agentId);
        // 如果代理人手机没有修改，更新
        if (agent.getMobile().equals(load.getMobile())) {
            genericDaoSupport.update(load.edit(agent));
        } else if (loads.size() > 0) {
            throw BusinessException.newInstance("400", "代理人手机不可重复！");
        }
        
    }

    /**
     * 列出二级代理
     *
     * @param primaryAgentCompanyId
     * @return
     */
    public List<Agent> listSecondaryAgent(Long primaryAgentCompanyId) {

        AgentCompany primaryAgentCompany = genericDaoSupport.load(AgentCompany.class, primaryAgentCompanyId);

        if (primaryAgentCompany.getPrimaryAgent() != null || primaryAgentCompany.getPrimaryAgentRate() != null){
            throw new BusinessException("500", "数据异常");
        }

        List<Agent> secondaryAgents = agentDao.listSecondaryAgent(primaryAgentCompany);

        return secondaryAgents;
    }

    /**
     * @param primaryAgentCompany
     * @return
     */
    @Override
    public Agent loadByAgentCompany(AgentCompany primaryAgentCompany) {

        Agent agent = genericDaoSupport.searchForObject("FROM Agent Where disabled = false AND company = :company ", "company", primaryAgentCompany, Agent.class);

        return agent;
    }

}
